//
//  ListenViewController.m
//  DialectShare
//
//  Created by timmy zhong on 3/21/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ListenViewController.h"
#import "CachedImage.h"
#import "AudioStreamer.h"
#import "User.h"
#import "DialectDB.h"
#import "UserDB.h"
#import "CommentViewController.h"
#import "UserDialectsViewController.h"

@interface ListenViewController ()
@property (nonatomic, retain) AudioStreamer *streamer;
@property (nonatomic, retain) UserProxy *userProxy;
@property (nonatomic, retain) DialectProxy *dialectProxy;

- (void)spinButton;
- (void)destoryStreamer;
- (void)createStreamer;
- (void)setPlayButtonImage:(UIImage *)image needSpinning:(BOOL)spinning;
- (void)showDialectOfUser;

@end

@implementation ListenViewController
@synthesize avatarContainer = _avatarContainer, name = _name, goodCount = _goodCount, badCount = _badCount, content = _content, followButton = _followButton, dialect = _dialect, streamer = _streamer, playButton = _playButton;
@synthesize userProxy = _userProxy, dialectProxy = _dialectProxy, canShowUserDialects = _canShowUserDialects;
- (id)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.canShowUserDialects = YES;
    }
    return self;
}

- (void)dealloc
{
    [self destoryStreamer];
    
    self.avatarContainer = nil;
    self.goodCount = nil;
    self.badCount = nil;
    self.name = nil;
    self.content = nil;
    self.followButton = nil;
    self.dialect = nil;
    
    self.playButton = nil;
    self.userProxy.delegate = nil;
    self.userProxy = nil;
    self.dialectProxy.delegate = nil;
    self.dialectProxy = nil;
    
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.name.text = self.dialect.user.name;
    CachedImage *avatar = nil;
    if (self.canShowUserDialects) {
        avatar = [[CachedImage alloc] initWithFrame:self.avatarContainer.bounds target:self selector:@selector(showDialectOfUser)];
    } else {
        avatar = [[CachedImage alloc] initWithFrame:self.avatarContainer.bounds];
    }
    [avatar showImageForUrl:self.dialect.user.avatar defaultImage:[[NSBundle mainBundle] pathForResource:@"user_icon" ofType:@"png"]];
    [self.avatarContainer addSubview:avatar];
    [avatar release];
    self.goodCount.text = [NSString stringWithFormat:@"(%d)", self.dialect.good];
    self.badCount.text = [NSString stringWithFormat:@"(%d)", self.dialect.bad];
    self.content.text = self.dialect.content;
    if (self.dialect.user.isFollow) {
        [self.followButton setTitle:@"取消关注" forState:UIControlStateNormal];
    } else {
        [self.followButton setTitle:@"加关注" forState:UIControlStateNormal];
    }
    [self createStreamer];
    
    _userProxy = [[UserProxy alloc] init];
    _userProxy.delegate = self;
    _dialectProxy = [[DialectProxy alloc] initWithDelegate:self];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.streamer stop];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)listen:(id)sender
{
    if (!self.streamer.isPlaying) {

        [self.streamer start];
        [self setPlayButtonImage:[UIImage imageNamed:@"loadingbutton.png"] needSpinning:YES];
    } else {
        [self.streamer stop];
    }
    
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    
}

- (void)spinButton
{
	[CATransaction begin];
	[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
	CGRect frame = [self.playButton frame];
	self.playButton.layer.anchorPoint = CGPointMake(0.5, 0.5);
	self.playButton.layer.position = CGPointMake(frame.origin.x + 0.5 * frame.size.width, frame.origin.y + 0.5 * frame.size.height);
	[CATransaction commit];
    
	[CATransaction begin];
	[CATransaction setValue:(id)kCFBooleanFalse forKey:kCATransactionDisableActions];
	[CATransaction setValue:[NSNumber numberWithFloat:2.0] forKey:kCATransactionAnimationDuration];
    
	CABasicAnimation *animation;
	animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
	animation.fromValue = [NSNumber numberWithFloat:0.0];
	animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
	animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear];
	animation.delegate = self;
	[self.playButton.layer addAnimation:animation forKey:@"rotationAnimation"];
    
	[CATransaction commit];
}

- (void)createStreamer
{
    if (self.streamer) {
        return ;
    }
    
    NSURL *url = [NSURL URLWithString:self.dialect.uri];
    _streamer  = [[AudioStreamer alloc] initWithURL:url];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(playbackStateChanged:)
     name:ASStatusChangedNotification
     object:_streamer];

}

- (void)destoryStreamer
{
    if (self.streamer) {
        [[NSNotificationCenter defaultCenter]
         removeObserver:self
         name:ASStatusChangedNotification
         object:_streamer];
		
		[self.streamer stop];
		self.streamer = nil;
    }
}

- (void)playbackStateChanged:(NSNotification *)aNotification
{
	if ([_streamer isWaiting])
	{
		[self setPlayButtonImage:[UIImage imageNamed:@"loadingbutton.png"] needSpinning:YES];
	}
	else if ([_streamer isPlaying])
	{
		[self setPlayButtonImage:[UIImage imageNamed:@"stopbutton.png"] needSpinning:NO];
	}
	else if ([_streamer isIdle])
	{
		[self setPlayButtonImage:[UIImage imageNamed:@"playbutton.png"] needSpinning:NO];
	}
}

- (void)setPlayButtonImage:(UIImage *)image needSpinning:(BOOL)spinning
{
    [self.playButton.layer removeAllAnimations];
    [self.playButton setImage:image forState:UIControlStateNormal];
    if (spinning) {
        [self spinButton];
    }
}

- (IBAction)follow:(id)sender
{
    User *user = [[User alloc] init];
    user.uid = self.dialect.uid;
    if (self.dialect.user.isFollow) {
        
        [_userProxy unfollow:user];
    } else {
        [_userProxy follow:user];
    }

    [user release];
}

- (IBAction)goodbad:(id)sender
{
    UIButton *button = (UIButton *)sender;
    if (button.tag == 1) {
        //good
        [_dialectProxy goodbad:YES dialect:self.dialect];
    } else {
        //bad
        [_dialectProxy goodbad:NO dialect:self.dialect];
    }
}

- (IBAction)comment:(id)sender
{
    CommentViewController *controller = [[CommentViewController alloc] init];
    controller.dialect = self.dialect;
    [self presentViewController:controller animated:YES completion:nil];
    [controller release];
}

- (void)showDialectOfUser
{
    UserDialectsViewController *controller = [[UserDialectsViewController alloc] init];
    controller.user = self.dialect.user;
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

#pragma mark - proxy delegate
- (void)requestFailWithProxy:(Proxy *)proxy
{
    
}
- (void)requestFinishWithProxy:(Proxy *)proxy
{
    if ([proxy isKindOfClass:[UserProxy class]]) {
        BOOL isFollow = self.dialect.user.isFollow;
        User *user = self.dialect.user;
        user.isFollow = !isFollow;
        if (user.isFollow) {
            [self.followButton setTitle:@"取消关注" forState:UIControlStateNormal];
        } else {
            [self.followButton setTitle:@"加关注" forState:UIControlStateNormal];
        }
        
        UserDB *db = [[UserDB alloc] init];
        [db addUsers:[NSArray arrayWithObject:user]];
        [db release];
        
    } else if ([proxy isKindOfClass:[DialectProxy class]]) {
        BOOL isGood = ((NSNumber *)proxy.object).boolValue;
        if (isGood) {
            self.dialect.good ++;
            self.goodCount.text = [NSString stringWithFormat:@"(%d)", self.dialect.good];
        } else {
            self.dialect.bad ++;
            self.badCount.text = [NSString stringWithFormat:@"(%d)", self.dialect.bad];
        }
        
        DialectDB *db = [[DialectDB alloc] init];
        [db addDialects:[NSArray arrayWithObject:self.dialect]];
        [db release];
    }
}









@end
